package com.demo.simpletestapp.exoplayer

import android.net.Uri
import android.os.Bundle
import android.view.Surface
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.impl.PreviewConfig
import androidx.databinding.DataBindingUtil.setContentView
import com.demo.simpletestapp.R
import com.google.android.exoplayer2.DefaultRenderersFactory
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.ui.PlayerView
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util

class LiveStreamActivity : AppCompatActivity() {
    private lateinit var playerView: PlayerView
    private lateinit var player: SimpleExoPlayer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_live_stream)

        playerView = findViewById(R.id.player_view)
        player = SimpleExoPlayer.Builder(this, DefaultRenderersFactory(this))
            .setTrackSelector(DefaultTrackSelector(this))
            .build()

        playerView.player = player

        val videoUri = Uri.parse("android.resource://$packageName/${R.raw.sea}")
//        val videoUri = Uri.parse("Your_Live_Stream_URL_here")
//        val dataSourceFactory = DefaultDataSourceFactory(this, "exoplayer-sample")

        // 获取摄像头视频流并创建 MediaSource
        val dataSourceFactory = DefaultDataSourceFactory(this, Util.getUserAgent(this, "Your App Name"))
//        val videoSource = ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(videoUri)

        val videoSource = ProgressiveMediaSource
            .Factory(dataSourceFactory)
            .createMediaSource(videoUri)
        player.repeatMode = Player.REPEAT_MODE_ALL
        player.prepare(videoSource)
        player.playWhenReady = true
    }

//    fun getCameraXSurface():Surface{
//        val previewConfig = PreviewConfig.Builder().build()
//        val preview = Preview(previewConfig)
//
//        preview.setOnPreviewOutputUpdateListener { previewOutput ->
//            val surfaceTexture = previewOutput.surfaceTexture
//            val surface = Surface(surfaceTexture)
//            // 在这里您可以使用这个Surface对象，例如用于创建MediaSource
//        }
//    }

    override fun onDestroy() {
        player.release()
        super.onDestroy()
    }
}